<template>
  <div class="my-posts">
    <div class="filter-bar-wrapper">
      <FilterBar
        :searchQuery="searchQuery"
        :status="status"
        showSearch
        showStatus
        @update:searchQuery="searchQuery = $event"
        @update:status="status = $event"
      />
    </div>

    <LoadingWrapper :loading="loading">
      <div>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部" name="all">
            <el-table 
              v-if="filteredPosts.length > 0"
              :data="paginatedPosts"
              style="width: 100%" 
              :cell-style="{ padding: '12px 0' }"
            >
              <el-table-column 
                prop="index" 
                label="序号" 
                width="80"
                align="center"
              />
              
              <el-table-column 
                prop="title" 
                label="书名" 
                min-width="180"
                align="center"
                show-overflow-tooltip
              />
              
              <el-table-column 
                prop="author" 
                label="作者" 
                min-width="120"
                align="center"
                show-overflow-tooltip
              />
              
              <el-table-column 
                prop="tags" 
                label="标签" 
                min-width="150"
                align="center"
              >
                <template #default="scope">
                  <el-tag
                    v-for="tag in scope.row.tags ? scope.row.tags.split(/\s+/).filter(tag => tag) : []"
                    :key="tag"
                    size="small"
                    class="mx-1"
                  >
                    {{ tag }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column 
                prop="like_count" 
                label="点赞量" 
                width="100"
                align="center"
              />
              
              <el-table-column 
                prop="rating" 
                label="综合评分" 
                width="100"
                align="center"
              />
              
              <el-table-column 
                prop="created_at" 
                label="发布时间" 
                width="180"
                align="center"
              >
                <template #default="scope">
                  {{ new Date(scope.row.created_at).toLocaleString() }}
                </template>
              </el-table-column>
              
              <el-table-column 
                prop="status" 
                label="状态" 
                width="100"
                align="center"
              >
                <template #default="scope">
                  <el-tag 
                    :type="scope.row.status === 1 ? 'success' : 'info'"
                    size="small"
                  >
                    {{ scope.row.status === 1 ? '已发布' : '已下架' }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column 
                label="操作" 
                width="200"
                fixed="right"
                align="center"
              >
                <template #default="{ row }">
                  <div class="operation-cell">
                    <el-tooltip content="编辑" placement="top">
                      <el-button type="primary" link @click="handleEdit(row)">
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </el-tooltip>

                    <el-tooltip :content="row.status === 0 ? '上架' : '下架'" placement="top">
                      <el-button
                        :type="row.status === 0 ? 'success' : 'warning'"
                        link
                        @click="row.status === 0 ? handlePublish(row) : handleUnpublish(row)"
                      >
                        <el-icon>
                          <Upload v-if="row.status === 0" />
                          <Download v-else />
                        </el-icon>
                      </el-button>
                    </el-tooltip>

                    <el-tooltip content="删除" placement="top">
                      <el-button 
                        type="danger" 
                        link 
                        @click="handleDelete(row)"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </LoadingWrapper>

    <div class="pagination-wrapper">
      <PaginationBar
        v-if="filteredPosts.length > 0"
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="filteredPosts.length"
        :pageSizes="[10, 15, 20, 25]"
        @pagination-change="handlePaginationChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { 
  Edit,
  Delete,
  Download,
  Upload,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getMyBooks, publishBook, unpublishBook, deleteBook } from '@/api/book'
import FilterBar from '@/components/filter/FilterBar.vue'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'
import { wsClient } from '@/utils/websocket'

const activeTab = ref('all')
const postsList = ref([])
const router = useRouter()

// 基础数据
const searchQuery = ref('')
const status = ref('1') // '1'表示全部，'2'表示已上架，'0'表示已下架
const currentPage = ref(1)
const pageSize = ref(10)

// 添加 loading 状态
const loading = ref(true)

// 过滤帖子
const filteredPosts = computed(() => {
  return postsList.value.filter(post => {
    // 标题或作者名称匹配搜索关键词
    const matchQuery = !searchQuery.value || 
      post.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      post.author.toLowerCase().includes(searchQuery.value.toLowerCase())
    
    // 状态筛选逻辑
    const matchStatus = status.value === '1' || 
      (status.value === '2' && post.status === 1) || 
      (status.value === '0' && post.status === 0)
    
    return matchQuery && matchStatus
  })
})

// 分页后的帖子列表
const paginatedPosts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPosts.value.slice(start, end)
})

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1  // 重置到第一页
  }
}

// 监听筛选条件变化，重置页码
watch([searchQuery, status], () => {
  currentPage.value = 1
})

// 获取书籍列表
const getBookList = async () => {
  try {
    loading.value = true
    const response = await getMyBooks()
    if (response.code === 200) {
      postsList.value = response.data.map((item, index) => ({
        ...item,
        index: index + 1,
        status: Number(item.status) 
      }))
    } else {
      ElMessage.error(response.message || '获取书籍列表失败')
    }
  } catch (error) {
    ElMessage.error('获取书籍列表失败')
  } finally {
    loading.value = false
  }
}

// 修改编辑处理函数
const handleEdit = (row) => {
  const routeData = router.resolve({
    path: `/my-post/edit/${row.id}`
  })
  window.open(routeData.href, '_blank')
}

// 上架书籍
const handlePublish = async (row) => {
  try {
    await publishBook(row.id)
    // 更新书籍状态
    row.status = Number(1)
    ElMessage.success('上架成功')
  } catch (error) {
    console.error('上架失败:', error)
    ElMessage.error(error.message || '上架失败，请稍后重试')
  }
}

// 下架书籍
const handleUnpublish = async (row) => {
  try {
    await unpublishBook(row.id)
    // 更新书籍状态
    row.status = Number(0)
    ElMessage.success('下架成功')
  } catch (error) {
    console.error('下架失败:', error)
    ElMessage.error(error.message || '下架失败，请稍后重试')
  }
}

// 删除书籍
const handleDelete = async (row) => {
  try {
    await deleteBook(row.id)
    ElMessage.success('删除成功')
    // 重新获取列表
    getBookList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 处理新书籍发布
const handleNewBookPublished = (bookData) => {
  console.log('收到新书籍发布通知:', bookData)
  // 刷新列表以显示新发布的书籍
  getBookList()
}

// 处理书籍状态变化
const handleBookStatusChange = ({ bookId, status, isDelete }) => {
  console.log('收到书籍状态变化通知:', bookId, status, isDelete)
  if (isDelete) {
    // 如果是删除操作，从列表中移除
    postsList.value = postsList.value.filter(post => post.id !== parseInt(bookId))
  } else {
    // 如果是上架/下架操作，更新状态
    const post = postsList.value.find(post => post.id === parseInt(bookId))
    if (post) {
      post.status = status
    }
  }
}

// 处理书籍更新
const handleBookUpdated = (bookData) => {
  // console.log('收到书籍更新通知:', bookData)
  // 查找并更新对应书籍
  const index = postsList.value.findIndex(post => post.id === parseInt(bookData.id))
  if (index !== -1) {
    // 更新书籍信息
    const originalPost = postsList.value[index]
    postsList.value[index] = {
      ...originalPost, // 保留原来的属性
      title: bookData.title,
      author: bookData.author,
      thoughts: bookData.thoughts,
      tags: bookData.tags,
      images: bookData.images,
      reading_url: bookData.reading_url,
      status: Number(bookData.status)
    }
  } else {
    getBookList()
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  getBookList()
  
  // 连接 WebSocket
  wsClient.connect()
  
  // 监听新书籍发布消息
  wsClient.on('new_book_published', handleNewBookPublished)
  
  // 监听书籍状态变化
  wsClient.on('book_status_change', handleBookStatusChange)
  
  // 监听书籍更新
  wsClient.on('book_updated', handleBookUpdated)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  // 移除监听器
  wsClient.off('new_book_published', handleNewBookPublished)
  wsClient.off('book_status_change', handleBookStatusChange)
  wsClient.off('book_updated', handleBookUpdated)
})
</script>

<style scoped>
.my-posts {
  padding: 20px;
}

.filter-bar-wrapper {
  display: flex;
  justify-content: flex-end;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

:deep(.el-dialog__body) {
  padding: 0 !important;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.title-cell {
  font-weight: 500;
  color: #303133;
  display: block;
  width: 100%;
}

.operation-cell {
  display: flex;
  justify-content: center;
  gap: 6px;
}

:deep(.el-tag) {
  margin: 0 4px;
}

:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 1000;
}

.el-icon {
  font-size: 18px;
}

:deep(.el-button) {
  padding: 0;
}

:deep(.dialog-footer) {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__footer .el-button) {
  padding: 6px 12px;
  font-size: 14px;
}

:deep(.el-dialog__body) {
  padding: 0 !important;
}

:deep(.el-table) {
  margin-bottom: 20px;
}
</style>
